#include <iostream>
#include <string>
#include <sstream>
#include <jsoncpp/json/json.h>
#include <memory>
// 实现序列化
bool serialize(const Json::Value &val, std::string &body)
{

    std::stringstream ss;
    // 实例化一个工厂类
    Json::StreamWriterBuilder swb;

    // 派生
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    // Json::StreamWriter*sw=swb.newStreamWriter();
    int ret = sw->write(val, &ss);
    if (ret != 0)
    {
        std::cout << "json serialize falied" << std::endl;
        return false;
    }
    body = ss.str();
    return true;

    /// delete sw;
}
// 实现反序列化
bool unserialize(const std::string &body, Json::Value &val)
{

    // 工厂类
    Json::CharReaderBuilder crb;
    // 派生
    std::string errs;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    bool ret = cr->parse(body.c_str(), body.c_str() + body.size(), &val, &errs);
    if (ret == false)
    {
        std::cout << "json unserialize falied" << errs << std::endl;
        return false;
    }
    return true;
}

int main()
{

    const char *name = "小明";
    int age = 12;
    const char *sex = "男";
    float score[3] = {33, 45, 34};
    Json::Value student;
    student["姓名"] = name;
    student["年龄"] = age;
    student["性别"] = sex;
    student["成绩"].append(score[0]);
    student["成绩"].append(score[1]);

    student["成绩"].append(score[2]);

    Json::Value fav;
    fav["书籍"] = "西游记";
    fav["运动"] = "游泳";

    student["爱好"] = fav;
    std::string body;
    serialize(student, body); // 把这个返回值存在body
    std::cout << body;

    Json::Value stu;
    std::string str = R"({"姓名":"夏黑","年龄":12,"成绩":[23,23])";//特殊的初始化方式
    bool ret = unserialize(str, stu);

    std::cout << "姓名" << stu["姓名"].asString() << std::endl;
    std::cout << "年龄" << stu["年龄"].asInt() << std::endl;
    for (int i = 0; i < stu["成绩"].size(); i++)
    {
        std::cout << "成绩" << stu["成绩"][i].asFloat() << std::endl;
    }

    return 0;
}